<?php


class BeeUrl{
	
	/**
	* 获取动作名称
	*
	* @access public
	* @return array
	*/
	public static function getAction(){
		return self::getSegment(2,"index");	
		
	}
	/**
	* 获取模块名称
	*
	* @access public
	* @return array
	*/
	public static function getMod(){
		return self::getSegment(1,"index");		
	}
	
	
	/**
	* 访问字段
	*
	* @access public
	* @return array
	*/
	public static function getSegment($pos,$default){
		$r= self::explode();		
		$res=$r[$pos]?$r[$pos]:"$default";
		return $res;
		
	}
	
	
	
	
	
	/**
	* 获得友好的URL访问
	*
	* @access public
	* @return array
	*/
	public static function explode($codeName="/code.php",$useDefine=true){
		//echo "REQUEST_URI=".$_SERVER['REQUEST_URI'];
		if($useDefine){
			if(defined(REWRITE_CODE_NAME)){			
				$codeName=REWRITE_CODE_NAME;			
			}
		}
		
		if(false === strpos($_SERVER['REQUEST_URI'], $codeName)){
			
			$res= explode("/",$_SERVER['REQUEST_URI']);
		}else{
			$res= explode("/",substr($_SERVER['REQUEST_URI'],1));
		}
		//var_dump($res);
		return $res;
	}
	
	
	
}


class BeeCaptcha{
	
	public static function validateCode($input,$codeName="beeValidateCode"){
		session_start();
		if(isset($_SESSION[$codeName])&& strlen($_SESSION[$codeName])>0 
		
		&&  strtoupper($_SESSION[$codeName])=== strtoupper($input)) { 
			$_SESSION[$codeName]=null; 
			 session_commit();
			  return true;
		}else{
			return false;			
		}
		
		
		
	}
	/**
	 * 生成随机素 移动出去? 或采用BeeString? 
	 * todo
	 *
	 * @param int $len
	 * @return string
	 */
	 public static function random($len)
	{
	session_start();
	$srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	mt_srand();
	$strs="";
	for($i=0;$i<$len;$i++){	
	$strs.=$srcstr[mt_rand(0,35)];
	}
	return strtoupper($strs);
	}
	
 public static  function captcha($width=50,$height=25,$len=4,$codeName="beeValidateCode"){
	 	
	 	

	$str=self::random(4); //随机生成的字符串
	$width = 50; //验证码图片的宽度
	$height = 25; //验证码图片的高度
	
	
	@header("Content-Type:image/png");
	$_SESSION[$codeName] = $str;
	//echo $str;
	$im=imagecreate($width,$height);
	//背景色
	$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
	//模糊点颜色
	$pix=imagecolorallocate($im,187,230,247);
	//字体色
	$font=imagecolorallocate($im,41,163,238);
	//绘模糊作用的点
	mt_srand();
	for($i=0;$i<1000;$i++)
	{
	imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);
	}
	imagestring($im, 5, 7, 5,$str, $font);
	imagerectangle($im,0,0,$width-1,$height-1,$font);
	imagepng($im);
	imagedestroy($im);

	 	
	 }
	
	
	
	
}


class BeeSafe{
	/**
	 * 
	 * 去掉xss不安全函数
	 * 来源
	 *http://quickwired.com/smallprojects/php_xss_filter_function.php
	 * @param String $val
	 * @return sring
	 */
	public static function  clearXSS($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
   
   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
   
      // &#x0040 @ search for the hex values
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // &#00064 @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   
   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   
   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
               $pattern .= '|';
               $pattern .= '|(&#0{0,8}([9|10|13]);)';
               $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return $val;
} 
	
	
}


class BeeUpFile{
	
	/**
	 * 上传文件 使用的 ipbupfile 
	 *
	 * @param string $path
	 * @param string $name
	 * @param string $ext
	 * @param string $max_file_size
	 * @return int
	 */
	public static  function upfile($path="./uploads",$name='',$fieldName="FILE_UPLOAD",$ext=array( 'gif', 'jpg', 'jpeg', 'png' ),$max_file_size='10000000'){
	require_once("up_load.php");
		
	  if(!file_exists($path)){mkdir($path,777,true);}
	
		$name=$name?$name:time();
	    $upload = new class_upload();
	    $upload->upload_form_field=$fieldName;
	    $upload->out_file_dir     = $path;
		$upload->out_file_name     = time();	
	    $upload->max_file_size    = $max_file_size;
	    $upload->make_script_safe = 1;
	    $upload->allowed_file_ext = $ext;
	    $upload->upload_process();
	    return $upload->error_no; 		
		
	}
	
	
	
}



class BeeValidateUtil{

/**
 * 判断是否属于email
 * 
 * *来自于wordpress 可能优化了 检测速度 ,也可能降低的检测速度
 * 这段代码为什么不这么写?
 * 	$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
	if (strpos($user_email, '@') === false || strpos($user_email, '.') === false) 
		return false;
		return preg_match($chars, $user_email);
		
 *
 * @param string $user_email
 * @return int
 */
	public static 	function isEmail($userEmail) {
		$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
		if (strpos($userEmail, '@') !== false && strpos($userEmail, '.') !== false) {
			if (preg_match($chars, $userEmail)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}


}

class BeeHttpUtil{

	/**
	 * 跳转到另外的页面
	 * 
	 *
	 * @param string $strUrl
	 */

	public static function sendRedirectheader($strUrl){
		header("Location: $strUrl");
		exit();
	}

	public static function noCache(){
		header('content-type: text/html; charset=utf-8');
		header('Expires: Fri, 14 Mar 1980 20:53:00 GMT');
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-cache, must-revalidate');
		header('Pragma: no-cache');
	}

	
	public static function buildUrl($param){
		$s="";
		foreach ($param as $key=>$value) {
			$s.="$key=$value&";
		}
		return $s;
	}
	
		public static function buildUrl2($param){
		$s="";
		foreach ($param as $key=>$value) {
			$s.="/$value";
		}
		return $s;
	}
	
	
	/**
 * 返回默认的数值请求
 *
 * @param string $key
 * @param string $default
 * @return int
 */

	public static function  getReqestIntValue($key,$default=0){
		$value=0;
		if(isset($_REQUEST[$key])){
			$value= (int)$_REQUEST[$key];
		}

		$value=($value)?$value:$default;

		return $value;
	}

/**
 * 返回默认的数值数组请求
 *
 * @param string $key
 * @param string $default
 * @return int
 */

	public static function  getReqestIntArray($key,$default=0){
		$value=0;
		$q=array();
		if(isset($_REQUEST[$key])){
			foreach ($_REQUEST[$key] as $rvalue) {
			$value= (int)$rvalue;
			$value=($value)?$value:$default;
			$q[]=$value;
			}
			
		}
		return $q;
	}	
	
	

	
		/**
 * 返回默认的数组请求
 *
 * @param string $key
 * @param string $default
 * @return int
 */

	public static function  containCheckError($keyArray){
		
		$q=array();		
		foreach ($keyArray as $key) {		
			//var_dump($key);	
			if( ( !isset($_REQUEST[$key[0]]) )  ||
				 ! ThinkValidation::check($_REQUEST[$key[0]],$key[1]) ){
				$error=array();
				$error[$key[0]]=$key[2];
				$q[]=$error;			
			}
		}
		
		if(count($q)<1) 
		{
			return false;
		}else {		
			return $q;
		}
		
	}	
	
		public static function  containCheckError2($keyArray,$strJoin="\r\n"){
		
		$errorStr="";		
		foreach ($keyArray as $key) {		
			//var_dump($key);	
			if( ( !isset($_REQUEST[$key[0]]) )  ||
				 ! ThinkValidation::check($_REQUEST[$key[0]],$key[1]) ){
				
				$errorStr.=$key[2].$strJoin;						
			}
		}
		return $errorStr;
		
		
	}	
	
	/**
 * 返回默认的数组请求
 *
 * @param string $key
 * @param string $default
 * @return int
 */

	public static function  getReqestKeyArray($filedNameArray,$trim=1){
		$value=0;
		$q=array();
		
		foreach ($filedNameArray as $key) {
			if(isset($_REQUEST[$key])){			
				$q[$key]=trim($_REQUEST[$key]);
			}
		}
		
		
		return $q;
	}	
	
	
	
	/**
 * 返回默认的值请求
 *
 * @param string $key
 * @param string $default
 * @return int
 */

	public static function getRequestValue($key,$default=0,$trim=1){
		$value=0;
		if(isset($_REQUEST[$key])){

			$value= $_REQUEST[$key];
		}
		$value=($trim)?trim($value):$value;
		$value=($value)?$value:$default;

		return $value;
	}



}


class BeeFileUtil{

	/**
 * *递归目录下所有文件
 *
 * @param string $path
 * @return void
 */	
	public static function deltree($path) {
		if (is_dir($path)) {
			if (version_compare(PHP_VERSION, '5.0.0') < 0) {
				$entries = array();
				if ($handle = opendir($path)) {
					while (false !== ($file = readdir($handle))) $entries[] = $file;
					closedir($handle);
				}
			} else {
				$entries = scandir($path);
				if ($entries === false) $entries = array(); // just in case scandir fail...
			}
			foreach ($entries as $entry) {
				if ($entry != '.' && $entry != '..') {
					deltree($path.'/'.$entry);
				}
			}
			return rmdir($path);
		} else {
			return unlink($path);
		}
	}








	public static  function appendToFile($fileName,$content){
		$f=fopen($fileName,"a+");
		if($f){
			fwrite($f,$content);
			fclose($f);
		}


	}


	function walk_tree($top,&$q){
		print $top;
		$q[]=$top;
		$path=dir($top);
		while(false!==($fileinfo=$path->read())){

			if($fileinfo<>"." &&$fileinfo<>".." ){
				//$fileinfo=$top.$fileinfo;
				print $fileinfo."\n";
				//$array[]=$fileinfo;

				if(is_dir($top."/".$fileinfo)){
					walk_tree($top."/".$fileinfo,$q);
				}

			}

		}



	}








}


class BeeDateTimeUtil{
	
	/**样式太少了
	 * 
	 * 
	 * 返回样式的时间列表 如1998-02-1 17:12:12
	 *
	 * @return string 
	 */
	public static function StrTimeNow(){
		return  date('Y-m-d H:i:s');
	}

	public static function StrYday($formDate='',$add=1){
		$date = new DateTime($formDate);
		$date->modify("+1 day");
		return $date->format("Y-m-d");		
	}
	
	


}



class BeeStringUtil{
	
	
	
/**
 * 
 * 来自于ecshop 
 * 
 * 计算字符串的长度（汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
public static function length($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}
	
	



	/**
 * 去掉后边界
 *
 * @param  $str
 * @param  $x
 * @param  $y
 * @return string
 */

	public static function  getContentL($str,$x,$y){
		$tem=strstr($str,$x);
		return substr($tem,0, strpos($tem,$y));
	}




	/**
 * 保留两边边界
 *
 * @param  $str
 * @param  $x
 * @param  $y
 * @return string
 */
	public static function  getContentLR($str,$x,$y){
		$tem=strstr($str,$x);
		//return substr($tem,0, strpos($tem,$y));
		return  substr($tem,0,strpos($tem,$y)).$y;

	}



	/**
 * 去掉两边边界
 *
 * @param  $str
 * @param  $x
 * @param  $y
 * @return 
 */

	public static function getConent($str,$x,$y){
		$temp=$str;
		if(($pos=strpos($str,$x))!==false){
			$temp=substr($str,$pos+strlen($x));
		}
		if(($pos=strpos($temp,$y))!==false){
			$temp=substr($temp,0,$pos);
		}
		return $temp;
	}



	/**
 * 保留两边边界,去掉辅助选项,$z为真边界
 *
 * @param  $str
 * @param  $x
 * @param  $y
 * @param  $z
 * @return string
 */
	public static function  getContentLRZ($str,$x,$y,$z){
		$tem=strstr($str,$x);
		//return substr($tem,0, strpos($tem,$y));
		return  substr($tem,0,strpos($tem,$y)).$z;

	}




	/**
 * 保留两边边界数组,去掉辅助选项,$z为真边界
 *
 * @param  $str
 * @param  $x
 * @param  $y
 * @return array
 */
	public static function  getContentArrayLRZ($str,$x,$y,$z){
		$tem=$str;
		$ret=array();
		while(false!==(strpos($tem,$x))){
			$tem=strstr($tem,$x);

			$pos=strpos($tem,$y);
			$ret[]=substr($tem,0,$pos).$z;
			$tem=substr($tem,$pos+1);
		}
		return $ret;

	}




	/**
 * 保留两边边界数组 验证后面一个
 *
 * @param  $str
 * @param  $x
 * @param  $y
 * @return array
 */
	public static  function  getContentArrayLR($str,$x,$y){
		$tem=$str;
		$ret=array();
		while(false!==(strpos($tem,$x))){
			$tem=strstr($tem,$x);

			$pos=strpos($tem,$y);
			$ret[]=substr($tem,0,$pos).$y;
			$tem=substr($tem,$pos+1);
		}
		return $ret;
	}












}





?>